package com.leetcode.根据算法进行分类.滑动窗口相关;

import java.util.Arrays;

/**
 * @author: ZhouBert
 * @date: 2021/4/6
 * @description: 80. 删除有序数组中的重复项 II
 * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/
 * 官方的快慢指针的想法也有独到之处！可以学学！
 */
public class B_80_删除有序数组中的重复项_II {
	static B_80_删除有序数组中的重复项_II action = new B_80_删除有序数组中的重复项_II();

	public static void main(String[] args) {
		test1();
		test2();
		test3();
	}


	public static void test1() {
		//5
		int[] nums = new int[]{1, 1, 1, 1, 2, 2, 3};
		int res = action.removeDuplicates(nums);
		System.out.println("array = " + Arrays.toString(nums));
		System.out.println("res = " + res);
	}

	public static void test2() {
		//7
		int[] nums = new int[]{0, 0, 1, 1, 1, 1, 2, 3, 3};
		int res = action.removeDuplicates(nums);
		System.out.println("array = " + Arrays.toString(nums));
		System.out.println("res = " + res);

	}

	public static void test3() {
		//6
		int[] nums = new int[]{1, 1, 1, 2, 2, 2, 3, 3};
		int res = action.removeDuplicates(nums);
		System.out.println("array = " + Arrays.toString(nums));
		System.out.println("res = " + res);
	}

	/**
	 * 一看就是滑动窗口
	 * 既然题目要求的是从 0-res-1 长度的数组，那么就是将数组的元素进行修改
	 *
	 * @param nums
	 * @return
	 */
	public int removeDuplicates(int[] nums) {
		int deleteCount = 0, len = nums.length;
		int lastValue = nums[0], count = 1, index = 1;
//		boolean firstFind = false;
		for (int i = 1; i < len; i++) {
			if (lastValue == nums[i]) {
				if (count == 2) {
//					if (!firstFind) {
//						firstFind = true;
//					}
					deleteCount++;
				} else {
					nums[index] = nums[i];
					index++;
					count++;
				}
			} else {
				nums[index] = nums[i];
				index++;
				count = 1;
			}
			lastValue = nums[i];
		}

		return len - deleteCount;
	}

}
